//
//  Node.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-7-5.
//  Copyright 2009 xhzhang. All rights reserved.
//

#import "Node.h"


@implementation Node

@synthesize parent;

- (id)init{
	if(self = [super init]){
		childs = [[NSMutableArray alloc] init];
	}
	return self;
}

- (NSInteger)nodeType{
	return NONE_NODE;
}

- (BOOL)appendChild:(Node *)child{
	[childs addObject:child];
	child.parent = self;
	return YES;
}

- (NSDictionary *)getAttributes{
	// 默认自己是没有属性的，只有 Element 可以有
	return nil;
}

/**
 * 获取节点名称，所有继承自该类的类，都要定义方法，来重载
 */
- (NSString *)getNodeName{
	return @"#NODE";
}


/**
 * 获取第一个子节点
 */
- (Node *)getFirstChild{
	Node *ret = nil;
	if([childs count] > 0){
		ret = [childs objectAtIndex:0];
	}
	return ret;
}

/**
 * 获取最后一个子节点
 */
- (Node *)getLastChild{
	Node *ret = nil;
	NSInteger len = [childs count];
	if(len > 0){
		ret = [childs objectAtIndex:(len - 1)];
	}
	return ret;
}

/**
 * 获取前一个和自己在平级关系上的节点
 */
- (Node *)getPreviousSibling{
	Node *ret = nil;
	if(parent != nil){
		NSArray *cs = [parent getChildNodes];
		NSInteger index = [cs indexOfObject:self];
		if(index > 0){
			ret = [cs objectAtIndex:(index - 1)];
		}
	}
	return ret;
}

/**
 * 获取后一个和自己在平级关系上的节点
 */
- (Node *)getNextSibling{
	Node *ret = nil;
	if(parent != nil){
		NSArray *cs = [parent getChildNodes];
		NSInteger index = [cs indexOfObject:self];
		NSInteger len = [cs count];
		if(index > 0 && index < (len - 1)){
			ret = [cs objectAtIndex:(index + 1)];
		}
	}
	return ret;
}

/**
 * 获取子节点
 */
- (NSArray *)getChildNodes{
	NSArray *ret = nil;
	if([childs count] > 0){
		ret = [NSArray arrayWithArray:childs];
	}
	return ret;
}

- (Node *)getChildByName:(NSString *)nodeName{
	Node *ret = nil;
	if(nodeName){
		int len = [childs count];
		Node *n1;
		NSString *en;
		for(int i = 0;i<len;i++){
			n1 = [childs objectAtIndex:i];
			en = [n1 getNodeName];
			if([en isEqualToString:nodeName]){
				ret = n1;
				break;
			}
		}
	}
	return ret;
}

- (BOOL)hasChild{
	return [childs count] > 0;
}


- (BOOL)hasAttributes{
	return NO;
}

- (NSString *)getValue{
	return nil;
}

- (NSString *)toXML{
	// TODO 所有子类均应该继承
	return @"";
}


- (void)dealloc{
	[childs removeAllObjects];
	[childs release];
	if(parent){
		[parent release];
	}
	[super dealloc];
}

@end
